package com.luke.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 读取一个文件的内容写入到另外一个文件
 * @Descrtption NioFileChannel03
 * @Author luke
 * @Date 2020/4/23
 **/
public class NioFileChannel03 {

    public static void main(String[] args) throws Exception{

        FileInputStream fileInputStream = new FileInputStream("E:\\netty\\a1.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\netty\\a2.txt");

        FileChannel inputStreamChannel = fileInputStream.getChannel();
        FileChannel outputStreamChannel = fileOutputStream.getChannel();

        //方式1
        //outputStreamChannel.transferFrom(inputStreamChannel,0,inputStreamChannel.size());

        //方式2
        ByteBuffer byteBuffer = ByteBuffer.allocate(5);
        while(true){
            int readLen = inputStreamChannel.read(byteBuffer);//从FileChannel读取数据，写入到ByteBuffer（状态为write）
            if( readLen == -1){
                break;
            }

            byteBuffer.flip();//读写翻转，写了多少就只能读取多少

            //从ByteBuffer读取数据，写入到FileChannel
            outputStreamChannel.write(byteBuffer);

            //byteBuffer.flip();
            byteBuffer.clear();
        }

        fileInputStream.close();
        fileOutputStream.close();

    }

}
